-module(triangle).
-compile(export_all).

% "abc", "ab", "bc", "ac"
% Points -> [$a, $b, $c] -> "abc"
% Lines -> ["ab", "ac", "bc"]

subset([], _S) -> true;
subset([H|T], S) ->
  lists:member(H, S) andalso
  subset(T, S).

connected(_Points, []) -> false;
connected(Points, [H|T]) ->
  subset(Points, H) orelse
  connected(Points, T).

on_a_line([P1, P2, P3], Lines) ->
  connected([P1, P2, P3], Lines).

triangle([P1, P2, P3], Lines) ->
  connected([P1,P2], Lines) andalso
  connected([P1,P3], Lines) andalso
  connected([P2,P3], Lines) andalso
  not on_a_line([P1,P2,P3], Lines).

comb(L, 1) ->
  [[I] || I <- L];
comb(L, N) when length(L) =:= N ->
  [L];
comb([H|T], N) ->
  C1 = comb(T, N-1),
  C2 = comb(T, N),
  [[H] ++ I || I <- C1] ++ C2. 

triple_points(Points) ->
  comb(Points, 3).

count(Points, Lines) ->
  TriplePoints = triple_points(Points),
  count(TriplePoints, Lines, 0, []).

count([], _, N, Triangles) -> [N, Triangles];
count([H|T], Lines, N, Triangles) ->
  case triangle(H, Lines) of
    true  -> count(T, Lines, N+1, Triangles ++ [H]);
    false -> count(T, Lines, N, Triangles)
  end.

count() ->
  Points = "abcefdghkij",
  Lines = ["abc","ahie","akjf","agd","bhkg","cijg","cefd"],
  count(Points, Lines).

test6() ->
  Points = [$a, $b, $c, $d],
  Lines = ["ab", "ac", "bc", "ad", "bcd"],
  true = 3 =:= count(Points, Lines),
  ok.

test5() ->
  Points = [$a, $b, $c],
  Points1 = [$a, $b, $c, $d],
  [[$a, $b], [$a, $c], [$b, $c]] = comb(Points, 2),
  [[$a, $b], [$a, $c], [$a, $d], [$b, $c], [$b, $d], [$c, $d]] = comb(Points1, 2),
  [[$a, $b, $c], [$a, $b, $d], [$a, $c, $d], [$b, $c, $d]] = comb(Points1, 3),
  ok.

test4() ->
  Points = [$a, $b, $c],
  Lines = ["ab", "ac", "bc"],
  Lines1 = ["ab", "ac", "bc", "abc"],
  true = triangle(Points, Lines),
  false = triangle(Points, Lines1),
  ok.

test3() ->
  Points = [$a, $b],
  Points1 = [$a, $d],
  Points2 = [$a, $b, $c],
  Lines = ["acb", "cd"],
  true = connected(Points, Lines),
  false = connected(Points1, Lines),
  true = connected(Points2, Lines),
  ok.

test2() -> 
  Points = [$a,$b],
  Line1 = "abc",
  true = subset(Points, Line1),
  Line2 = "acd",
  false = subset(Points, Line2),
  ok.
